import json
import os

from flask import render_template
from flask import Flask, request, Response
from flask_restful import Api, Resource

app = Flask(__name__)
api = Api(app)

# 存储自定义接口配置
endpoints = {}


class DynamicEndpoint(Resource):
    def get(self, path):
        print(path)
        return self._process_request('GET', path)

    def post(self, path):
        return self._process_request('POST', path)

    def delete(self, path):
        print(path)
        return self._process_request('DELETE', path)

    def put(self, path):
        return self._process_request('PUT', path)

    def _process_request(self, method, path):
        config = endpoints.get((method, path), {})
        if not config:  # 如果接口未定义，返回 404 错误
            return {'error': 'Endpoint not found'}, 404
        # 构造响应--定义什么返回什么
        response = config.get('response', {'message': 'Success'})
        # response = {
        #     'status': config.get('status_code', 200),
        #     'headers': config.get('headers', {}),
        #     'body': config.get('response', {'message': 'Success'})
        # }
        response_json = json.dumps(response, ensure_ascii=False)
        return Response(response_json, mimetype='application/json')


# 注册动态路由
api.add_resource(DynamicEndpoint, '/<path:path>',
                 methods=['GET', 'POST', 'PUT', 'DELETE'])

# 确保静态路由优先级高于动态路由
@app.route('/list')
def list_interfaces():
    """渲染自定义接口列表页面"""
    # 将 endpoints 转换为模板期望的格式
    interfaces = []
    for (method, path), config in endpoints.items():
        interfaces.append({
            'endpoint': path,
            'methods': [method],
            'response': config.get('response', {})  # 新增：传递 response 到模板
        })
    return render_template('interface_list.html', interfaces=interfaces)

#页面注册接口
# @app.route('/register')
# def register_interface():
#     """渲染注册自定义接口的页面"""
#     return render_template('register_interface.html')

@app.route('/add_endpoint', methods=['POST'])
def register_endpoint():
    data = request.get_json()
    method = data.get('method')
    path = data.get('path')
    response = data.get('response')
    add_endpoint(method, path, response)
    save_endpoints()
    return {'message': 'Endpoint added successfully'}


@app.route('/delete_endpoint', methods=['POST'])
def delete_endpoint():
    data = request.get_json()
    method = data.get('method')
    path = data.get('path')
    if (method, path) in endpoints:
        del endpoints[(method, path)]
        save_endpoints()
        return {'message': 'Endpoint deleted successfully'}
    else:
        return {'message': 'Endpoint not found'}, 404


def catch_all(path):
    return DynamicEndpoint().dispatch_request()(path)


def add_endpoint(method, path, response, status_code=200, headers=None):
    """
    添加/更新接口配置
    :param method: HTTP方法（大写）
    :param path: 接口路径
    :param response: 响应内容
    :param status_code: 状态码
    :param headers: 响应头
    """
    endpoints[(method.upper(), path)] = {
        'response': response,
        'status_code': status_code,
        'headers': headers or {}
    }


# 定义保存 endpoints 的文件路径
ENDPOINTS_FILE = 'endpoints.json'

def save_endpoints():
    """将 endpoints 保存到本地 JSON 文件"""
    print("Saving endpoints...")
    print(endpoints)
    try:
        # 先删除旧文件
        if os.path.exists(ENDPOINTS_FILE):
            try:
                os.remove(ENDPOINTS_FILE)
            except Exception as e:
                print(f"Error deleting old endpoints file: {e}")
                return  # 如果删除失败，直接返回，不进行保存操作
        # 将 endpoints 的键转换为字符串
        endpoints_str_keys = {str(k): v for k, v in endpoints.items()}
        with open(ENDPOINTS_FILE, 'w', encoding='utf-8') as f:
            json.dump(endpoints_str_keys, f, ensure_ascii=False, indent=4)
    except Exception as e:
        print(f"Error saving endpoints: {e}")


def load_endpoints():
    """从本地 JSON 文件加载 endpoints"""
    if os.path.exists(ENDPOINTS_FILE):
        try:
            with open(ENDPOINTS_FILE, 'r', encoding='utf-8') as f:
                global endpoints
                endpoints_str_keys = json.load(f)
                # 将字符串键转换回元组
                endpoints = {eval(k): v for k, v in endpoints_str_keys.items()}
        except Exception as e:
            print(f"Error loading endpoints: {e}")

